<?php
namespace  Common\Org\Request;
/*
 * URL处理类
 */
class OAuthUtil {
    public static $boundary = '';

    /**
     * @param $input 要编码的字符串或数组
     * @return array|mixed|string
     * 对数组或字符串进行编码
     */
    public static function urlencode_rfc3986($input) {
        if (is_array($input)) {
            return array_map(array('\Common\Org\Request\OAuthUtil', 'urlencode_rfc3986'), $input);//20140609修改，添加命名空间
        } else if (is_scalar($input)) {
            return str_replace(
                '+',
                ' ',
                str_replace('%7E', '~', rawurlencode($input))
            );
        } else {
            return '';
        }
    }


    // This decode function isn't taking into consideration the above
    // modifications to the encoding process. However, this method doesn't
    // seem to be used anywhere so leaving it as is.
    /**
     * @param $string 要解码的字符串
     * @return string
     * 字符串解码，与urlencode_rfc3986相对
     */
    public static function urldecode_rfc3986($string) {
        return urldecode($string);
    }

    /**
     * @param $params 参数数组
     * @return string
     * 生成URL格式的字符串并返回
     */
    public static function build_http_query($params) {
        if (!$params) return '';

        // Urlencode both keys and values
        $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
        $values = OAuthUtil::urlencode_rfc3986(array_values($params));
        $params = array_combine($keys, $values);

        // Parameters are sorted by name, using lexicographical byte value ordering.
        // Ref: Spec: 9.1.1 (1)
        uksort($params, 'strcmp');

        $pairs = array();
        foreach ($params as $parameter => $value) {
            if (is_array($value)) {
                // If two or more parameters share the same name, they are sorted by their value
                // Ref: Spec: 9.1.1 (1)
                natsort($value);
                foreach ($value as $duplicate_value) {
                    $pairs[] = $parameter . '=' . $duplicate_value;
                }
            } else {
                $pairs[] = $parameter . '=' . $value;
            }
        }

        // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
        // Each name-value pair is separated by an '&' character (ASCII code 38)
        return implode('&', $pairs);
    }

    /**
     * @param $params 参数数组
     * @return string
     * 生成URL格式的字符串并返回
     */
    public static function build_http_query_multi($params) {
        if (!$params) return '';

        // Urlencode both keys and values
        $keys = array_keys($params);
        $values = array_values($params);
        $params = array_combine($keys, $values);

        // Parameters are sorted by name, using lexicographical byte value ordering.
        // Ref: Spec: 9.1.1 (1)
        uksort($params, 'strcmp');
        $pairs = array();
        self::$boundary = $boundary = uniqid('------------------');
        $MPboundary = '--'.$boundary;
        $endMPboundary = $MPboundary. '--';
        $multipartbody = '';

        foreach ($params as $parameter => $value)
        {
            if( in_array($parameter,array("pic","image")) && $value{0} == '@' )
            {
                $url = ltrim( $value , '@' );
                $content = file_get_contents( $url );
                $filename = reset( explode( '?' , basename( $url ) ));
                $mime = self::get_image_mime($url);

                $multipartbody .= $MPboundary . "\r\n";
                $multipartbody .= 'Content-Disposition: form-data; name="' . $parameter . '"; filename="' . $filename . '"'. "\r\n";
                $multipartbody .= 'Content-Type: '. $mime . "\r\n\r\n";
                $multipartbody .= $content. "\r\n";
            }
            else
            {
                $multipartbody .= $MPboundary . "\r\n";
                $multipartbody .= 'content-disposition: form-data; name="'.$parameter."\"\r\n\r\n";
                $multipartbody .= $value."\r\n";
            }
        }
        $multipartbody .=  $endMPboundary;
        return $multipartbody;

    }

    /**
     * @param $file
     * @return string
     * 获取MIME类型
     */
    public static function get_image_mime( $file ){
        $ext = strtolower(pathinfo( $file , PATHINFO_EXTENSION ));
        switch( $ext )
        {
            case 'jpg':
            case 'jpeg':
                $mime = 'image/jpg';
                break;

            case 'png';
                $mime = 'image/png';
                break;

            case 'gif';
            default:
                $mime = 'image/gif';
                break;
        }
        return $mime;
    }
}